package com.dwx.guli.service.oss.controller.admin;

import com.dwx.guli.service.oss.service.FileService;
import com.dwx.guli.service.base.exception.GuliException;
import com.dwx.guli.service.base.result.R;
import com.dwx.guli.service.base.result.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Api(tags = "阿里云文件管理")
@CrossOrigin //跨域
@RestController
@Slf4j
@RequestMapping("/admin/oss/file")
public class FileController {
    @Autowired
    FileService fileService;
    /**
     * 文件上传
     * @param file
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module){
        try {
            InputStream inputStream = file.getInputStream();
            String upload = fileService.upload(inputStream, module, file.getOriginalFilename());
            return R.ok().data("url",upload).message("文件上传成功");
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public R removeFile(
            @ApiParam(value = "要删除的文件路径", required = true)
            @RequestBody String url){
        fileService.removeFile(url);
        return R.ok().message("文件刪除成功");
    }
}
